package per.turtle.common.excel.handler;

import com.alibaba.excel.context.AnalysisContext;
import lombok.extern.slf4j.Slf4j;
import per.turtle.common.excel.kit.Validators;

import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认的 AnalysisEventListener
 *
 * @author lengleng
 * @author L.cm
 */
@Slf4j
public class DefaultAnalysisEventListener extends ListAnalysisEventListener<Object> {

    private final List<Object> list = new ArrayList<>();

    private final Map<Long, Set<ConstraintViolation<Object>>> errors = new ConcurrentHashMap<>();

    private Long lineNum = 1L;

    @Override
    public Map<Long, Set<ConstraintViolation<Object>>> getErrors() {
        return errors;
    }

    @Override
    public List<Object> getList() {
        return list;
    }

    @Override
    public void invoke(Object o, AnalysisContext analysisContext) {
        lineNum++;

        Set<ConstraintViolation<Object>> violations = Validators.validate(o);
        if (!violations.isEmpty()) {
            errors.put(lineNum, violations);
        } else {
            list.add(o);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.debug("Excel read analysed");
    }

}
